/**
 * 系统管理（用户/角色/权限）API 服务
 * 负责与后端 /api/v1/admin 接口交互
 */

import { API_CONFIG } from '../config.js';

const BASE_URL = API_CONFIG.ADMIN.BASE_URL;

function buildQueryString(params = {}) {
  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === null || value === '') return;
    if (Array.isArray(value)) {
      value.forEach(item => searchParams.append(key, item));
    } else {
      searchParams.append(key, value);
    }
  });
  const query = searchParams.toString();
  return query ? `?${query}` : '';
}

function getToken() {
  if (typeof window === 'undefined') return null;
  return (
    localStorage.getItem('auth_token') ||
    sessionStorage.getItem('auth_token') ||
    null
  );
}

async function request(url, options = {}) {
  const token = getToken();
  const headers = {
    Accept: 'application/json',
    ...(options.body ? { 'Content-Type': 'application/json' } : {}),
    ...(options.headers || {}),
  };
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const response = await fetch(url, {
    ...options,
    headers,
  });

  const contentType = response.headers.get('Content-Type') || '';
  const isJson = contentType.includes('application/json');

  if (!response.ok) {
    let message = `请求失败：${response.status}`;
    let body = null;
    if (isJson) {
      try {
        body = await response.json();
        message = body?.message || message;
      } catch (err) {
        // ignore parse error
      }
    } else {
      try {
        const text = await response.text();
        if (text) message = text;
      } catch (err) {
        // ignore
      }
    }
    const error = new Error(message);
    error.status = response.status;
    if (body) error.body = body;
    throw error;
  }

  if (!isJson) {
    return null;
  }

  const result = await response.json();
  return result?.data ?? result;
}

export const adminUserService = {
  async getList(params = {}) {
    return request(`${BASE_URL}/users${buildQueryString(params)}`);
  },

  async getDetail(id) {
    return request(`${BASE_URL}/users/${id}`);
  },

  async create(payload) {
    return request(`${BASE_URL}/users`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async update(id, payload) {
    return request(`${BASE_URL}/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });
  },

  async resetPassword(id, payload) {
    return request(`${BASE_URL}/users/${id}/reset-password`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async updateStatus(id, payload) {
    return request(`${BASE_URL}/users/${id}/status`, {
      method: 'PATCH',
      body: JSON.stringify(payload),
    });
  },

  async assignRole(id, payload) {
    return request(`${BASE_URL}/users/${id}/role`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });
  },

  async remove(id) {
    return request(`${BASE_URL}/users/${id}`, {
      method: 'DELETE',
    });
  },
};

export const adminRoleService = {
  async getList(params = {}) {
    return request(`${BASE_URL}/roles${buildQueryString(params)}`);
  },

  async getDetail(id) {
    return request(`${BASE_URL}/roles/${id}`);
  },

  async create(payload) {
    return request(`${BASE_URL}/roles`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async update(id, payload) {
    return request(`${BASE_URL}/roles/${id}`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });
  },

  async updatePermissions(id, payload) {
    return request(`${BASE_URL}/roles/${id}/permissions`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });
  },

  async remove(id) {
    return request(`${BASE_URL}/roles/${id}`, {
      method: 'DELETE',
    });
  },

  async listRoleUsers(id, params = {}) {
    return request(`${BASE_URL}/roles/${id}/users${buildQueryString(params)}`);
  },

  async addRoleUsers(id, payload) {
    return request(`${BASE_URL}/roles/${id}/users`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async removeRoleUsers(id, payload) {
    return request(`${BASE_URL}/roles/${id}/users`, {
      method: 'DELETE',
      body: JSON.stringify(payload),
    });
  },
};

export const adminPermissionService = {
  async getList(params = {}) {
    return request(`${BASE_URL}/permissions${buildQueryString(params)}`);
  },

  async getDetail(id) {
    return request(`${BASE_URL}/permissions/${id}`);
  },

  async create(payload) {
    return request(`${BASE_URL}/permissions`, {
      method: 'POST',
      body: JSON.stringify(payload),
    });
  },

  async update(id, payload) {
    return request(`${BASE_URL}/permissions/${id}`, {
      method: 'PUT',
      body: JSON.stringify(payload),
    });
  },

  async remove(id) {
    return request(`${BASE_URL}/permissions/${id}`, {
      method: 'DELETE',
    });
  },

  async getTree() {
    return request(`${BASE_URL}/permissions/tree`);
  },
};


